package com.winit.schedule.job.tracker.event;

import com.winit.schedule.core.event.EventHandler;
import com.winit.schedule.core.utils.NetUtils;
import com.winit.schedule.job.tracker.JobTrackerContext;
import com.winit.schedule.job.tracker.conf.JobConfiguration;
import com.winit.schedule.job.tracker.sms.SmsSender;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TaskTrackerEventHandler implements EventHandler<TaskTrackerChangeEvent> {

    private static final Logger logger = LoggerFactory.getLogger(TaskTrackerEventHandler.class);

    private JobTrackerContext jobTrackerContext;

    private String            localIP;

    private SmsSender smsSender;

    private int alertSmsInvervalMin;

    private String[] smsAlertTo;

    private boolean develoyMode;

    private static final Map<String, Long> LASTER_SEND_MAP = new ConcurrentHashMap<String, Long>();

    public TaskTrackerEventHandler(JobTrackerContext jobTrackerContext){
        this.jobTrackerContext = jobTrackerContext;
        this.develoyMode = jobTrackerContext.getConf().getBoolean(JobConfiguration.DEVELOP_MODE,
                JobConfiguration.DEFAULT_DEVELOP_MODE);
        this.alertSmsInvervalMin = jobTrackerContext.getConf().getInt(JobConfiguration.ALERT_SMS_INVERVAL_MIN,
                JobConfiguration.DEFAULT_ALERT_SMS_INVERVAL_MIN);

        if (this.alertSmsInvervalMin < JobConfiguration.DEFAULT_ALERT_SMS_INVERVAL_MIN) {
            this.alertSmsInvervalMin = JobConfiguration.DEFAULT_ALERT_SMS_INVERVAL_MIN;
        }
        this.smsAlertTo = jobTrackerContext.getConf().getStrings(JobConfiguration.ALERT_SMS_TO);
        this.smsSender = this.jobTrackerContext.getSmsSender();
        localIP = NetUtils.getLocalIP();
    }

    @Override
    public void handle(TaskTrackerChangeEvent event) {

        if ( TaskTrackerEventType.DISCONNECT.equals(event.getType()) && null != event.getTaskTrackers()) {
            // 创建基本邮件信息
            String subject = "TaskTracker disconnect from uschedule[" + localIP + "]";

            String tts = StringUtils.join(event.getTaskTrackers(), "\n\r");
            String content = "TaskTracker disconnect, TaskTracker UUID :\n\r " + tts;

            sendSms(event.getTaskTrackers());
            jobTrackerContext.getMailHelper().sendTextMail(subject, content);
        } else if (TaskTrackerEventType.TIMEOUT_TASKITEM.equals(event.getType())) {
            String subject = "Abnormal timeout task item for uschedule[" + localIP + "]";
            StringBuilder content = new StringBuilder();
            content.append("\n\r")
                    .append("以下定时任务已经停止运行，请登录uschedule控制台（菜单：【异常任务项】）查看并可完成恢复操作。")
                    .append("\n\r")
                    .append("The following tasks have been stopped, please login to the uschedule console to complete the recovery operation.")
                    .append("\n\r");
            content.append("TaskItems: " + "\n\r" + event.getTimeoutTaskItems());
            jobTrackerContext.getMailHelper().sendTextMail(subject, content.toString());
        }

    }

    public void sendSms(List<String> disconnectedTTS) {
        try {
            if (!develoyMode && null != smsAlertTo && smsAlertTo.length > 0) {
                StringBuilder content = new StringBuilder();
                for (String taskTrackerUUID : disconnectedTTS) {
                    Long lastetSendtime =  0L;
                    Long currentTime = System.currentTimeMillis();
                    if (LASTER_SEND_MAP.containsKey(taskTrackerUUID)) {
                        lastetSendtime = LASTER_SEND_MAP.get(taskTrackerUUID);
                    }
                    if (lastetSendtime == 0 || (currentTime - lastetSendtime > (1000 * 60 * alertSmsInvervalMin))) {
                        LASTER_SEND_MAP.put(taskTrackerUUID, currentTime);

                        int idx = taskTrackerUUID.lastIndexOf("$");
                        if (idx > 0) {
                            content.append(taskTrackerUUID.substring(0, idx)).append("; ");
                        }
                    }

                }

                if (!"".equals(content.toString())) {
                    String tts = "USchedule disconnected: \n\r" + content.toString();
                    smsSender.sendSms(tts, smsAlertTo);
                }
            }

        } catch (Throwable e) {
            logger.error("=========> 发送告警短信失败", e);
        }
    }
}
